package com.xiaoxi.open.codemodel.core.impl;

import com.xiaoxi.open.codemodel.common.enumeration.CodeModelSystemEnums;
import com.xiaoxi.open.codemodel.common.enumeration.CodeModelUserEnums;
import com.xiaoxi.open.codemodel.domain.BmsCodeModel;
import com.xiaoxi.open.codemodel.sqltemplate.Bindings;
import com.xiaoxi.open.codemodel.sqltemplate.SqlMeta;
import com.xiaoxi.open.codemodel.sqltemplate.SqlTemplate;
import com.xiaoxi.open.codemodel.sqltemplate.SqlTemplateEngin;
import com.xiaoxi.open.common.exception.BaseException;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;
import java.util.Map;

/**
 * @Author xiaoxi
 * @ProjectName springcloudbms
 * @PackageName com.xiaoxi.open.codemodel.core.impl
 * @ClassName SeqCodeModelServiceImpl
 * @Description TODO
 * @Date 2023/2/22 15:57
 * @Version 1.0
 */
@Service("seq")
@Slf4j
public class SeqCodeModelServiceImpl extends AbstractCodeServiceImpl {

    @Resource
    private JdbcTemplate jdbcTemplate;

    @Override
    public List<Map<String, Object>> getCodeList(BmsCodeModel codeModel) {

        String SQL = codeModel.getSqlText();
        if (StringUtils.isEmpty(SQL)) {
            throw new BaseException(CodeModelUserEnums.SQL_TEXT_EMPTY);
        }
        if (!SQL.toUpperCase().startsWith("SELECT")) {
            throw new BaseException(CodeModelUserEnums.SQL_MUST_SELECT);
        }

        return queryForListByWenSQLTemplate(codeModel.getSqlText());

    }


    private List<Map<String, Object>> queryForListByWenSQLTemplate(String sqlText) {

        SqlTemplateEngin sqlTemplateEngin = new SqlTemplateEngin();

        //从字符串读取sql模板内容,还可以从单独的文件读取
        SqlTemplate sqlTemplate = sqlTemplateEngin.getSqlTemplate(sqlText);

        Bindings bind = new Bindings();

        Map<String, Object> objectMap = generatorCondition();
        for (Map.Entry<String, Object> entry : objectMap.entrySet()) {
            bind.bind(entry.getKey(), entry.getValue());
        }

        SqlMeta sqlMeta = null;
        try {
            sqlMeta = sqlTemplate.processStatic(bind); //可传map对象或javabean对象
        } catch (Exception e) {
            log.error("发生异常,请联系管理员：{}", e.getMessage());
            throw new BaseException(CodeModelSystemEnums.SYSTEM_ERROR.getCode(), e.getMessage());
        }
        assert sqlMeta != null;
        return jdbcTemplate.queryForList(sqlMeta.getSql());

    }


}
